package com.sumer.brain.common.utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import lombok.extern.java.Log;

import java.util.List;
import java.util.function.Function;

@Log
public class SimpleDataListener<T, R> implements ReadListener<T> {

    private static final int BATCH_COUNT = 100;
    private List<T> cachedDataList;
    private final Function<List<T>, R> function;

    public SimpleDataListener(Function<List<T>, R> function) {
        this.function = function;
        this.cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    }

    @Override
    public void invoke(T t, AnalysisContext context) {
        if (cachedDataList == null) {
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
        cachedDataList.add(t);

        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData(cachedDataList);
            clearCache();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if (!cachedDataList.isEmpty()) {
            saveData(cachedDataList);
        }
    }

    private void saveData(List<T> list) {
        function.apply(list);
    }

    private void clearCache() {
        cachedDataList.clear();
    }
}
